//
//  ModelView.swift
//  Automobile
//
//  Created by erkebulan elzhan on 8/8/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import UIKit
import SnapKit


protocol ModalElementProtocol: class {
    func selectElement (modal: ModalView.ModalType?, customID: Int?)
    func didClear (modal: ModalView.ModalType)
}

final class ModalElement: UIView {
    
    // MARK: - Outlets
    
    private lazy var closeBtn: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "close"), for: .normal)
        return btn
    }()
    
    private lazy var columnStack: UIStackView = {
        let stack = UIStackView()
        stack.axis = .vertical
        stack.alignment = .fill
        stack.distribution = .equalSpacing
        stack.spacing = 0.0
        
        return stack
    }()
    
    private lazy var hintLbl: UILabel = {
        let lbl = UILabel()
        lbl.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        lbl.textColor = .greyColor
        lbl.textAlignment = .left
        lbl.sizeToFit()
        return lbl
    }()
    
    private lazy var valueLbl: UILabel = {
        let lbl = UILabel()
        lbl.font = UIFont.systemFont(ofSize: 15, weight: .semibold)
        lbl.textColor = .black
        lbl.textAlignment = .left
        lbl.sizeToFit()
        return lbl
    }()
    
    private lazy var textField: UITextField = {
        let field = UITextField()
        field.backgroundColor = .clear
        field.font = UIFont.systemFont(ofSize: 15, weight: .semibold)
        field.textColor = .black
        field.delegate = self
        return field
    }()
    
    lazy var checkBox: ViewWithImage = {
        let view = ViewWithImage()
        view.layer.cornerRadius = 4.0
        view.layer.borderWidth = 1
        return view
    } ()
    
    // MARK: - Props
    
    public var modal: ModalView.ModalType!
    public weak var delegate: ModalElementProtocol!
    
    private var withTF: Bool = false
    private var withCheckBox: Bool = false
    
    // unique identificator of modal element
    private var customID: Int?
    
    
    // MARK: - Actions
    
    @objc private func onRemove (sender: UIButton) {
        if (delegate != nil) {
            if let _modal = self.modal {
                delegate.didClear(modal: _modal)
            } else {
                delegate.didClear(modal: ModalView.ModalType.dvigatel) // Optional, sending just for fun
            }
        } else {
            textField.text = ""
        }
    }
    
    
    // MARK: - Init
    
    init () {
        super.init(frame: .zero)
        addView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public func updateUI (value: String?,
                          placeholder: String? = nil,
                          withTF: Bool=false,
                          withCheckbox: Bool=false,
                          customID: Int?=nil,
                          keyboardType: UIKeyboardType?=nil) {
        self.withTF = withTF
        self.withCheckBox = withCheckbox
        self.customID = customID
        
        if withTF {
            if value != nil && !value!.isEmpty {
                self.textField.text = value
                self.showTextField()
            } else {
                self.hideTextField()
            }
            
            if keyboardType != nil {
                self.textField.keyboardType = keyboardType!
            }
        } else {
            if value != nil && value != "" {
                self.valueLbl.text = value!
                self.showValueMode()
            } else {
                self.hideValueMode()
            }
        }
        
        if placeholder != nil {
            self.hintLbl.text = placeholder!
        }
        
        if (withCheckbox) {
            self.showCheckBox()
        } else if value != nil && !value!.isEmpty{
            self.showCloseBtn()
        }
        
    }
    
    public func turnOfCheckBox () {
        self.didDeselectCheckbox()
        self.checkBox.isSelected = false
    }
    
    public func turnOnCheckBox () {
        self.didSelectCheckbox()
        self.checkBox.isSelected = true
    }
    
    public func getTextFieldValue () -> String {
        return self.textField.text ?? ""
    }
    
    public func closeTextField () {
        self.textField.resignFirstResponder()
    }
    
    public func setTextFieldText (_ text: String?) {
        self.textField.text = text
        self.showTextField()
    }
    
    
    // MARK: - UI
    
    private func addView () {
        self.clipsToBounds = true
        self.layer.cornerRadius = 5
        self.backgroundColor = .whiteBlueColor
        self.addSubview(columnStack)
        
        columnStack.addArrangedSubview(hintLbl)
        columnStack.snp.makeConstraints { (make) in
            make.trailing.equalToSuperview().inset(38)
            make.leading.equalToSuperview().inset(16)
            make.top.bottom.equalToSuperview().inset(8)
        }
        closeBtn.addTarget(self, action: #selector(onRemove(sender:)), for: .touchUpInside)

        let tap = UITapGestureRecognizer(target: self, action: #selector(didSelectView(sender:)))
        self.addGestureRecognizer(tap)
    }
    
    private func showTextField () {
        columnStack.addArrangedSubview(textField)
        textField.becomeFirstResponder()
        
        textField.snp.makeConstraints { (make) in
            make.height.equalTo(18)
        }
        self.showCloseBtn()
    }
    
    private func hideTextField () {
        textField.removeFromSuperview()
        closeBtn.removeFromSuperview()
        columnStack.removeArrangedSubview(textField)
    }
    
    private func showValueMode () {
        self.hintLbl.font = .systemFont(ofSize: 12, weight: .regular)
        columnStack.addArrangedSubview(valueLbl)
    }
    
    private func hideValueMode () {
        self.hintLbl.font = .systemFont(ofSize: 14, weight: .regular)
        valueLbl.removeFromSuperview()
        closeBtn.removeFromSuperview()
        columnStack.removeArrangedSubview(valueLbl)
    }
    
    private func showCheckBox () {
        self.addSubview(checkBox)
        checkBox.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.trailing.equalToSuperview().inset(16)
            make.height.width.equalTo(16)
        }
    }
    
    private func showCloseBtn () {
        self.addSubview(closeBtn)
        closeBtn.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.trailing.equalToSuperview().inset(16)
            make.height.width.equalTo(14)
        }
    }
    
    private func didSelectCheckbox () {
        checkBox.addIcon(icon: UIImage(named: "correct"))
        checkBox.backgroundColor = UIColor(red: 47/255, green: 130/255, blue: 210/255, alpha: 1)
        checkBox.layer.borderColor = UIColor.clear.cgColor
    }
    
    private func didDeselectCheckbox () {
        if checkBox.iconView.image != nil {
            self.checkBox.addIcon(icon: nil)
        }
        
        checkBox.backgroundColor = .clear
        checkBox.layer.borderColor = UIColor.greyBlue.cgColor
    }
}



extension ModalElement {
    @objc private func didSelectView (sender: UITapGestureRecognizer) {
        if (delegate != nil && !withCheckBox) {
            delegate.selectElement(modal: self.modal, customID: nil)
        } else if withTF {
            self.showTextField()
        } else if withCheckBox {
            delegate.selectElement(modal: nil, customID: self.customID)
        }
    }
}

extension ModalElement: UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
    }
}
